package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import model.Race;
import service.RaceService;
import service.impl.RaceServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @Author: 燕子豪
 * @Date: 2022/12/17 19:59
 */
@WebServlet("/raceUpdate")
public class RaceUpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        RaceService raceService = new RaceServiceImpl();

        //解析前段json数据
        BufferedReader bufferedReader = new BufferedReader(request.getReader());
        String line = null;
        final StringBuilder json = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            json.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(json.toString());

        //new一个race用于接收数据
        Race race = new Race();
        race.setRname(jsonObject.getString("rname"));
        race.setCid(Integer.parseInt(jsonObject.getString("cid")));
        race.setDesc(jsonObject.getString("desc"));
        race.setRurl(jsonObject.getString("rurl"));

        //执行方法并存储返回结果
        JSONObject message = new JSONObject();
        if (raceService.update(race)) {
            message.put("statue", "1");
            message.put("raceMsg", "更新成功");
        }else{
            message.put("statue", "0");
            message.put("raceMsg", "更新失败");
        }
        response.getWriter().write(message.toString());
    }
}
